package com.lx.code;

import java.io.*;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-08-09 14:54:35
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-08-09     张李鑫                     1.0         1.0 Version
 */
public class DataPack {

    /**
     * <p>
     * 把数据拆分成一个二维水族
     * </p>
     *
     * @param data         原始数据
     * @param packetLength
     * @return byte[][]
     * @Author zlx
     * @date 2021/8/9
     */
    public static byte[][] dataPacket(byte[] data, int packetLength) throws Exception {
        if (data != null && packetLength > 0) {
            int curson = 0;
            int dataLength = data.length;
            int lengthRemain = dataLength % packetLength;
            int updateCount = lengthRemain == 0 ? dataLength / packetLength : dataLength / packetLength + 1;
            byte[][] result = new byte[updateCount][];

            for (int i = 0; i < updateCount; ++i) {

                byte[] updateData;
                if (i == updateCount - 1) {
                    int length = dataLength - packetLength * (updateCount - 1);
                    updateData = new byte[length];
                    System.arraycopy(data, curson, updateData, 0, length);
                } else {
                    updateData = new byte[packetLength];
                    System.arraycopy(data, curson, updateData, 0, packetLength);
                    curson += packetLength;
                }

                result[i] = updateData;
            }

            return result;
        } else {
            throw new Exception("调用数据分包出错，参数错误");
        }
    }

    public static void main(String[] args) throws IOException {
        byte[]bytes= new byte[10];
        byte[] padding = padding(bytes, 64);

        long l1 = System.nanoTime();
        File file1 = new File("/Users/user/Desktop/index1.txt");
        FileOutputStream fileOutputStream1 = new FileOutputStream(file1);
        for (int i = 0; i < 1000_000; i++) {
            fileOutputStream1.write(padding);
        }
        System.out.println((System.nanoTime() - l1)/100_0000);
    }

    public static byte[] padding(byte[] data, int groupLength) {
        int remainder = data.length % groupLength;
        int paddingLen = groupLength;
        if (0 != remainder) {
            paddingLen = groupLength - remainder;
        }

        byte[] padding = copyOf(data, data.length + paddingLen);

        for (int i = 0; i < paddingLen; ++i) {
            padding[data.length + i] = Byte.valueOf(String.valueOf(paddingLen));
        }

        return padding;
    }

    public static byte[] copyOf(byte[] original, int newLength) {
        byte[] copy = new byte[newLength];
        System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
        return copy;


    }


}
